#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <unistd.h>
#include <libxml/SAX.h>
#include <string.h>
#include <stdbool.h>
#include <pthread.h>
#include "config.h"
#include "dwmstatus_types.h"
#include "curl_sax.h"
#include "gmail.h"

String gmail_formated;

pthread_mutex_t gmail_exclusive = PTHREAD_MUTEX_INITIALIZER;

void gmail_format_mail(Mail *current) {
  String buffer;

  snprintf(buffer, sizeof(buffer), MAIL_FORMAT, current->unread);
  set_gmail(buffer);
}

void set_gmail(char *my_mail) {
  pthread_mutex_lock(&gmail_exclusive);
  COPY(gmail_formated, my_mail, sizeof(gmail_formated));
  pthread_mutex_unlock(&gmail_exclusive);
}

void get_gmail(char *dest, size_t size) {
  pthread_mutex_lock(&gmail_exclusive);
  COPY(dest, gmail_formated, size);
  pthread_mutex_unlock(&gmail_exclusive);
}

void gmail_start() {
  pthread_t mail_thread;
  pthread_create(&mail_thread, NULL, gmail_loop, NULL);
}

void *gmail_loop(void *ptr) {
  for (;;sleep(UPDATE_MAIL_INTERVAL))
    gmail_update_mail();
}

void gmail_update_mail() {
  xmlSAXHandler mySaxHandler;
  Mail myMail;

  memset(&myMail, 0, sizeof(myMail));
  gmail_set_sax_handler(&mySaxHandler);

  curl_sax_get_data(GOOGLE_MAIL_URL, &mySaxHandler, &myMail);
  gmail_format_mail(&myMail);
}

void gmail_set_sax_handler(xmlSAXHandler *sax_handler) {
  memset(sax_handler, 0, sizeof(xmlSAXHandler));
  sax_handler->initialized = XML_SAX2_MAGIC;
  sax_handler->startElementNs = gmail_sax_on_start;
  sax_handler->endElementNs = gmail_sax_on_end;
  sax_handler->characters = gmail_sax_on_char;
}

void gmail_sax_on_start(void *ctx,
			const xmlChar *localname,
			const xmlChar *prefix,
			const xmlChar *uri,
			const int nb_namespaces,
			const xmlChar **namespaces,
			int nb_attributes,
			int nb_defaulted,
			const xmlChar **pattributes) {
  Mail *mail = ctx;
  
  if (!strcmp(FULL_COUNT, localname))
    mail->current_buffer = mail->unread;

} // gmail_sax_start

void gmail_sax_on_end(void *ctx,
		      const xmlChar *localname, 
		      const xmlChar *prefix,
		      const xmlChar *uri) {
  Mail *mail = ctx;
  mail->current_buffer = NULL;
}

void gmail_sax_on_char(void *data, const xmlChar *ch, int len) {
  Mail *mail = data;

  if (mail->current_buffer != NULL) {
    memcpy(mail->current_buffer + strlen(mail->current_buffer), ch, len);
  }
}


